const list_m = require('./groupData')
const config = require('./config')
const store = require('../store/index').default
const Vue = require('vue').default

let socket
// 连接服务器
function connectServer() {
  return new Promise((resolve, reject) => {
    // 连接服务器
    socket = io(config.ioUrl)

    socket.on('connect', () => {
      console.log('用户已连接');

      resolve()
    })

    // 接受群消息
    socket.on('groupMsg', (o) => {
      getMsg(o, false)
      if (o.code === 0) {
        console.log(o);
        list_m.default.addList({ id: o.id, isConfirm: true, avatarUrl: o.avatarUrl, name: o.name, uid: o.uid, nick: o.nick, num: o.num, con: o.con })
      }
    })

    // 接受群图片
    socket.on('groupMsgImg', (o) => {
      getMsg(o, false)
      if (o.code === 0) {
        console.log(o);
        list_m.default.addList({ id: o.id, isConfirm: true, avatarUrl: o.avatarUrl, name: o.name, uid: o.uid, nick: o.nick, num: o.num, imgUrl: o.imgUrl, isImg: true })
      }
    })

    // 接受撤回消息
    socket.on('groupWithDraw', o => {
      console.log(o);
      if (o.code === 0) {
        let item = list_m.default.groupList.find(item1 => item1.num === o.num)
        if (item) {
          let message = item.messages.find(item2 => item2.id === o.id)
          if (message) {
            message.isWithDraw = true
            message.con = ''
            message.imgUrl = ''
          }
        }
      }
    })
  })
}

function getMsg(oo = {}, showSMsg = true, showEMsg = true) {
  if (oo.code === 0) {
    showSMsg && oo.msg && Vue.prototype.$message.success(oo.msg)
  } else if (oo.code === 205) {
    Vue.prototype.$message.error('请登录 - ' + oo.msg)
  } else {
    showEMsg && oo.msg && Vue.prototype.$message.error(oo.msg)
  }
}

// 封装的发送消息的函数
function sendMsg(msgName, o = {}, cb = () => { }, showSMsg = true, showEMsg = true) {
  let token = localStorage.getItem('token')
  socket.emit(msgName, { ...o, token }, (oo = {}) => {
    getMsg(oo, showSMsg, showEMsg)
    cb(oo)
  })
}

// 断开服务器连接
function closeServer() {
  socket.close()
}

// 修改昵称
function updateNickName(nick) {
  socket.emit('updateNick', nick)
}

export default {
  sendMsg,

  connectServer,
  closeServer,
  updateNickName
}